# myapp/redis_manager.py
import redis
from threading import local
from base_config.cache_config import REDIS_PORT, REDIS_HOST, REDIS_PASSWORD
from typing import Dict, Optional

DEFAULT_ALIAS = "default"


class RedisPoolManager:
    _instance = None
    _thread_local = local()

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        if not hasattr(self, "_initialized"):
            # 从 Django settings 或你的 config 中读取配置
            self.redis_config = {
                "host": REDIS_HOST,
                "port": REDIS_PORT,
                "password": REDIS_PASSWORD,
                "db": 1,  # 关键：使用不同的 DB，避免和缓存冲突！
                "max_connections": 20,
                "socket_connect_timeout": 5,
                "socket_timeout": 5,
                "retry_on_timeout": True,
            }
            self._pools: Dict[str, redis.ConnectionPool] = {}
            self._initialized = True

    def get_pool(self, alias=DEFAULT_ALIAS) -> redis.ConnectionPool:
        """获取或创建连接池"""
        if alias not in self._pools:
            pool_config = self.redis_config.copy()
            # 如果需要，可以根据 alias 提供不同的配置
            self._pools[alias] = redis.ConnectionPool(**pool_config)
        return self._pools[alias]

    def get_client(self, alias=DEFAULT_ALIAS) -> redis.Redis:
        """获取 Redis 客户端实例 (用于复杂操作)"""
        pool = self.get_pool(alias)
        return redis.Redis(
            connection_pool=pool, decode_responses=True
        )  # decode_responses 很重要

    def close_all(self):
        """关闭所有连接池 (可在 Django shutdown 信号中调用)"""
        for pool in self._pools.values():
            pool.disconnect()
        self._pools.clear()


# 创建全局实例
_redis_manager = RedisPoolManager()


# redis的连接
def get_redis_client(alias=DEFAULT_ALIAS) -> redis.Redis:
    """
    :param alias:连接别名（可用于多redis实例）
    :return: redis。Redis客户端端
    """
    return _redis_manager.get_client(alias=alias)
